package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.sun.deploy.net.HttpResponse;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @version V1.11
 * @ClassName:
 * @Description:
 * @Date
 */
@Controller
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private SysUserService sysUserService;
    
    @GetMapping(value = "/list")
    @ResponseBody
    public void list(HttpServletResponse response, Model model, Integer page, Integer limit, String realName, Integer roleId) throws IOException {
        
        List<SysUser> userList = sysUserService.list(page, limit, realName, roleId);

        int count = sysUserService.count(realName, roleId);
        TableVO tableVO = new TableVO(0, count, userList, "");
    
        String json = JSON.toJSONString(tableVO);
    
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(json);

    }
    
    @GetMapping("/add")
    public String toAdd() {
        return "add";
    }
    @PostMapping("/add")
    public String toAdd(Model model,@Valid SysUser sysUser,BindingResult bindingResult){
        if  (   bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError: fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }
        }
        return "add";
    }
    
    @GetMapping("/update/{id}")
    public String update(Model model,@PathVariable("id") String id){
        SysUser sysUser = sysUserService.selectId(id);
        model.addAttribute("sysUser",sysUser);
        return "update";
    }
    
    @PostMapping("/update")
    @ResponseBody
    public String  update(Model model,  SysUser sysUser){
        Integer result = sysUserService.update(sysUser);
        return result.toString();
    }
}
    
